<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 资源中心->菜单管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-container>
                <el-aside width="420px">
                    <el-row>
                        <el-select v-model="selectAppCode" class="handle-select" @change="loadMenuTree" placeholder="选择应用">
                            <el-option v-for="item in appList"
                                       :label="item.appName"
                                       :value="item.appCode">
                                <span style="float: left">{{ item.appName }}</span>
                            </el-option>
                        </el-select>
                    </el-row>
                    <el-row style="border: #97a8be solid 1px; height:480px">
                        <div class="tree-container">
                            <el-tree node-key="id"
                                     ref="tree"
                                     class="tree filter-tree"
                                     highlight-current
                                     :indent="0"
                                     :data="menuTree"
                                     :expand-on-click-node="false"
                                     @node-click="loadMenuDetail"
                                     @node-contextmenu="rightClickMenu"
                                     :props="defaultProps">
                            </el-tree>
                            <div id="contextMenu" style="top: 215px; left: 122px;">
                                <ul>
                                    <li id="m_add_node" @click="handleAddMenu">新增同级节点</li>
                                    <li id="m_add_child" @click="handleAddChildMenu">新增下级节点</li>
                                    <li id="m_del_node" @click="handleDelMenu">删除节点</li>
                                </ul>
                            </div>
                        </div>
                    </el-row>
                </el-aside>
                <el-main>
                    <el-form ref="form" :model="formData" label-width="100px">
                        <el-row :gutter="10">
                            <el-col :md="12">
                                <el-form-item label="菜单编码">
                                    <el-input v-model="formData.menuCode"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :md="12">
                                <el-form-item label="菜单名称">
                                    <el-input v-model="formData.menuName"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :md="12">
                                <el-form-item label="菜单级别">
                                    <el-input v-model="formData.menuLevel" disabled="disabled"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :md="12">
                                <el-form-item label="顺序编号">
                                    <el-input v-model="formData.orderNo"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :md="12">
                                <el-form-item label="是否叶子">
                                    <el-radio-group v-model="formData.isLeaf">
                                        <el-radio-button v-for="item in yesnoList" :label="item.value">
                                            {{ item.label }}
                                        </el-radio-button>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :md="12">
                                <el-form-item label="菜单类型">
                                    <el-select v-model="formData.menuType" class="handle-select" disabled="disabled">
                                        <el-option v-for="item in menuTypeList"
                                                   :label="item.label"
                                                   :value="item.value">
                                            <span style="float: left">{{ item.label }}</span>
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :md="24">
                                <el-form-item label="上级菜单">
                                    <el-select v-model="formData.parentId" class="handle-select" disabled="disabled">
                                        <el-option v-for="item in parentMenuList"
                                                   :label="item.label"
                                                   :value="item.value">
                                            <span style="float: left">{{ item.label }}</span>
                                        </el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :md="12">
                                <el-form-item label="是否隐藏">
                                    <el-radio-group v-model="formData.isHidden">
                                        <el-radio-button v-for="item in yesnoList" :label="item.value">
                                            {{ item.label }}
                                        </el-radio-button>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :md="12">
                                <el-form-item label="是否可用">
                                    <el-radio-group v-model="formData.isEnable">
                                        <el-radio-button v-for="item in yesnoList" :label="item.value">
                                            {{ item.label }}
                                        </el-radio-button>
                                    </el-radio-group>
                                </el-form-item>
                            </el-col>
                            <el-col :md="24">
                                <el-form-item label="菜单地址" v-show="formData.isLeaf=='Y'">
                                    <el-input v-model="formData.targetUrl"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <el-row>
                        <el-col :md="24" style="text-align:right;">
                            <el-button-group style="float:left" v-show="formData.id!=null&&formData.isLeaf=='Y' ? true:false">
                                <el-button type="primary" @click="handleAddResource">新增</el-button>
                                <el-button type="primary" @click="handleRefreshResource">刷新</el-button>
                            </el-button-group>
                            <el-button type="primary" @click="handleSaveMenu">保 存</el-button>
                        </el-col>
                    </el-row>
                    <el-table border class="table"
                              v-show="formData.id!=null&&formData.isLeaf=='Y'?true:false"
                              :data="tableData"
                              ref="multipleTable"
                              header-cell-class-name="table-header"
                    >
                        <el-table-column type="selection" width="55" align="center"></el-table-column>
                        <el-table-column prop="resourceCode" label="功能编码" width="180"></el-table-column>
                        <el-table-column prop="resourceName" label="功能名称" width="150"></el-table-column>
                        <el-table-column prop="targetUrl" label="资源URL"></el-table-column>
                        <el-table-column label="操作" width="130" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" icon="el-icon-edit"
                                           @click="handleEditResource(scope.$index, scope.row)">
                                    编辑
                                </el-button>
                                <el-button type="text" icon="el-icon-delete" class="red"
                                           @click="handleDeleteResource(scope.$index, scope.row)">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="pagination" v-show="formData.id!=null&&formData.isLeaf=='Y'?true:false">
                        <el-pagination
                                background
                                layout="total, prev, pager, next"
                                :current-page="query.pageVo.pageNo"
                                :page-size="query.pageVo.pageSize"
                                :total="pageTotal"
                                @current-change="handlePageChange"
                        ></el-pagination>
                    </div>
                </el-main>
            </el-container>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="资源信息" :visible.sync="editVisible" width="60%" :lock-scroll="false">
            <el-form ref="form" :model="resourceFormData" label-width="70px">
                <el-form-item label="资源名称">
                    <el-input v-model="resourceFormData.resourceName"></el-input>
                </el-form-item>
                <el-form-item label="资源编码">
                    <el-input v-model="resourceFormData.resourceCode"></el-input>
                </el-form-item>
                <el-form-item label="所属菜单">
                    <el-select v-model="resourceFormData.menuId" class="handle-select" disabled="disabled">
                        <el-option v-for="item in resourceMenuList"
                                   :label="item.label"
                                   :value="item.value">
                            <span style="float: left">{{ item.label }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="资源类型">
                    <el-radio-group v-model="resourceFormData.resourceType">
                        <el-radio-button v-for="item in resourceTypeList" :label="item.value">
                            {{ item.label }}
                        </el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="匹配方式">
                    <el-radio-group v-model="resourceFormData.matchType">
                        <el-radio-button v-for="item in matchTypeList" :label="item.value">
                            {{ item.label }}
                        </el-radio-button>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="资源URL">
                    <el-input v-model="resourceFormData.targetUrl"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleSaveResource">保 存</el-button>
                <el-button @click="editVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import {fetchDictByIndex} from '../../api/resic/dictionary';
    import { OnionUtils } from '../../utils/onion-utils';
    import { listApp } from '../../api/appic/appInfo';
    import {doFindMenus, doGetMenu, doSaveMenu, doDeleteMenu} from '../../api/resic/menu';
    import {doFindResource, doGetResource, doSaveResource, doDeleteResource} from '../../api/resic/resource';
    import "@/components/plugins/ztree/jquery.ztree.all.js";
    import "@/components/plugins/ztree/jquery.ztree.exhide.js";
    import "@/components/plugins/ztree/metroStyle/metroStyle.css";

    export default {
        name: 'menuPage',
        data() {
            return {
                query: {
                    data: {
                    },
                    pageVo: {
                        pageNo: 1,
                        pageSize: 10
                    }
                },
                editVisible: false,
                pageTotal: 0,
                idx: -1,
                id: -1,
                formData: {},
                contextMenuData: {},
                resourceFormData: {},
                selectAppCode: "",
                parentMenuList: [],
                menuTypeList: [],
                yesnoList: [],
                appList: [],
                matchTypeList: [],
                resourceTypeList: [],
                resourceMenuList: [],
                tableData: [],
                menuTree: [],
                defaultProps: {
                    label: 'title',
                    children: 'subs'
                }
            };
        },
        created() {
            this.initData();
            this.menuVisible = true;
        },
        //方法区
        methods: {
            //初始化页面数据
            initData() {
                //初始化下拉框
                fetchDictByIndex('onion.common.yes-no,onion.menu.type,onion.resource.type' +
                    ',onion.resource.match.type').then(res => {
                    this.yesnoList = res.data['onion.common.yes-no'];
                    this.menuTypeList = res.data['onion.menu.type'];
                    this.resourceTypeList = res.data['onion.resource.type'];
                    this.matchTypeList = res.data['onion.resource.match.type'];
                });
                let appQueryParam = {
                    param: {},
                    pageVo: { pageNo: 1, pageSize: 100 }
                };
                listApp(appQueryParam).then(res => {
                    this.appList = res.data;
                });
            },

            //加载菜单树
            loadMenuTree(){
                if(!OnionUtils.isEmpty(this.selectAppCode)){
                    doFindMenus(this.selectAppCode).then(result =>{
                        this.menuTree = result.data;
                    })
                }
            },

            //加载菜单信息
            loadMenuDetail(data){
                let pNode = this.getMenuData(this.menuTree, data.pId);
                this.parentMenuList.length = 0;
                if(pNode != null){
                    this.parentMenuList.push(pNode);
                }
                doGetMenu(data.id).then(result =>{
                    this.formData = result.data;
                    this.handleRefreshResource();
                })
            },
            //查找菜单节点数据
            getMenuData(treeData, menuId){
                for(let i=0; i<treeData.length;i++){
                    if(treeData[i].id == menuId){
                        return {"value":Number(treeData[i].id), "label":treeData[i].title};
                    }
                    if(treeData[i].subs && !OnionUtils.isEmpty(treeData[i].subs)){
                        let menuNode = this.getMenuData(treeData[i].subs, menuId);
                        if(menuNode != null){
                            return menuNode;
                        }
                    }
                }
                return null;
            },

            //右键菜单
            rightClickMenu(event, data, node, comp){
                this.showContextMenu(data, event.x, event.y);
            },

            //显示ZTree右键菜单
            showContextMenu(data, x, y) {
                this.contextMenuData = {};
                if(!data || !data.id || OnionUtils.isEmpty(data.id)){
                    return;
                }
                //
                this.contextMenuData = data;
                if ( data.pId==-1 || data.id==data.pId ) {
                    $("#m_add_node").hide();
                    $("#m_add_child").show();
                    $("#m_del_node").show();
                }else{
                    this.contextMenuData = data;
                    $("#m_add_node").show();
                    $("#m_add_child").show();
                    $("#m_del_node").show();
                }
                $("#contextMenu ul").show();
                y += document.body.scrollTop;
                x += document.body.scrollLeft;
                $("#contextMenu").css({"top":y+"px", "left":x+"px", "visibility":"visible"});
                $("body").bind("mousedown", this.onBodyMouseDown);                    
            },

            //隐藏ZTree右键菜单
            hideContextMenu() {
                if ($("#contextMenu")){
                    $("#contextMenu").css({"visibility": "hidden"});
                }
                $("body").unbind("mousedown", this.onBodyMouseDown);
            },

            //鼠标左键点击事件
            onBodyMouseDown(event){
                if (!(event.target.id == "contextMenu" || $(event.target).parents("#contextMenu").length>0)) {
                    this.hideContextMenu();
                }
            },

            //新增同级菜单节点
            handleAddMenu(event){
                var curNode = this.contextMenuData;
                if(!OnionUtils.isEmpty(curNode.id)){
                    let pNode = this.getMenuData(this.menuTree, curNode.pId);
                    this.parentMenuList.length = 0;
                    if(pNode != null){
                        this.parentMenuList.push(pNode);
                    }
                    let menuType = (curNode.id==curNode.pId || curNode.pId=="-1")?"application":"menu";
                    this.formData = {"parentId":Number(curNode.pId),
                                     "menuType":"menu",
                                     "isLeaf":"Y",
                                     "isHidden":"N",
                                     "isEnable":"Y"};
                }
                this.hideContextMenu();
            },

            //新增下级菜单节点
            handleAddChildMenu(event){
                if(!OnionUtils.isEmpty(this.contextMenuData.id)){
                    let curNode = this.getMenuData(this.menuTree, this.contextMenuData.id);
                    this.parentMenuList.length = 0;
                    if(curNode != null){
                        this.parentMenuList.push(curNode);
                    }
                    this.formData = {"parentId":Number(this.contextMenuData.id),
                                     "menuType":"menu",
                                     "isLeaf":"Y",
                                     "isHidden":"N",
                                     "isEnable":"Y"};
                }
                this.hideContextMenu();
            },

            //删除菜单节点
            handleDelMenu(){
                if(!OnionUtils.isEmpty(this.contextMenuData.id)){
                    // 二次确认删除
                    this.$confirm('确定要删除吗？', '提示', {
                        type: 'warning'
                    }).then(() =>{
                        doDeleteMenu(this.contextMenuData.id).then(result =>{
                            if(result.code == 0){
                                this.$message.success('删除成功');
                                this.loadMenuTree();
                            }else{
                                this.$alert("删除出错:"+result.message);
                            }
                        });
                    }).catch(() =>{
                        this.$alert("删除出错！");
                    });
                }
                this.hideContextMenu();
            },

            //保存菜单
            handleSaveMenu(){
                doSaveMenu(this.formData).then(result=>{
                    if(result.code != 0){
                        this.$alert("菜单保存成功！");
                    }else{
                        this.formData = result.data;
                    }
                });
            },

            //刷新资源列表
            handleRefreshResource(){
                let queryParam = {"menuId":this.formData.id};
                doFindResource(queryParam).then(result=>{
                    this.tableData = result.data.rows;
                    this.pageTotal = result.data.total || 10;
                });
            },

            //新增资源信息
            handleAddResource(){
                if(OnionUtils.isEmpty(this.formData.id)){
                    this.$alert("未选择菜单节点，或菜单信息未保存！");
                    return;
                }
                this.editVisible = true;
                this.resourceMenuList = [{"label":this.formData.menuName, "value":this.formData.id}];
                this.resourceFormData = {"menuId" : this.formData.id,
                                         "appCode" : this.formData.appCode,
                                         "matchType" : "exact",
                                         "resourceType" : "function"};
            },

            //编辑资源信息
            handleEditResource(index, row) {
                this.idx = index;
                this.resourceMenuList = [{"label":this.formData.menuName, "value":this.formData.id}];
                this.resourceFormData = row;
                this.editVisible = true;
            },

            //保存资源信息
            handleSaveResource(){
                if(OnionUtils.isEmpty(this.resourceFormData.menuId)){
                    this.$alert("未选择菜单节点，或菜单信息未保存！");
                    return;
                }
                doSaveResource(this.resourceFormData).then(result=>{
                    this.$message.success("资源信息保存成功！");
                    this.handleRefreshResource();
                    this.editVisible = false;
                });
            },

            //删除资源信息
            handleDeleteResource(index, row){
            },

            //翻页操作
            handlePageChange(){
                this.$set(this.query, 'pageIndex', val);
                this.getData();
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 10px;
    }

    .handle-select {
        width: 100%;
    }

    .handle-input {
        width: 100%;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .mt10 {
        margin-top: 10px;
    }

    .pr10 {
        padding-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }

    /* 树形结构节点添加连线 */
    .tree /deep/ .el-tree-node {
        position: relative;
        padding-left: 16px;
    }

    .tree /deep/ .el-tree-node__children {
        padding-left: 16px;
    }

    .tree /deep/ .el-tree-node :last-child:before {
        height: 38px;
    }

    .tree /deep/ .el-tree > .el-tree-node:before {
        border-left: none;
    }

    .tree-container /deep/ .el-tree > .el-tree-node:after {
        border-top: none;
    }

    .tree /deep/ .el-tree-node:before {
        content: "";
        left: -4px;
        position: absolute;
        right: auto;
        border-width: 1px;
    }

    .tree /deep/ .el-tree-node:after {
        content: "";
        left: -4px;
        position: absolute;
        right: auto;
        border-width: 1px;
    }
    .tree /deep/ .el-tree-node__expand-icon.is-leaf {
        display: none;
    }

    .tree /deep/ .el-tree-node:before {
        border-left: 1px dashed #b8b9bb;
        bottom: 0px;
        height: 100%;
        top: -26px;
        width: 1px;
    }

    .tree /deep/ .el-tree-node:after {
        border-top: 1px dashed #b8b9bb;
        height: 20px;
        top: 12px;
        width: 24px;
    }

    div#contextMenu {
        z-index: 9999;
        position:fixed;
        visibility:hidden;
        top:0;
        background-color: #555;
        text-align: left;
        padding: 2px;
    }

    div#contextMenu ul li{
        margin: 1px 0;
        padding: 0 5px;
        cursor: pointer;
        list-style: none outside none;
        background-color: #DFDFDF;
    }

</style>